<?php
/**
 * User: Hufeng
 * Date: 2017/12/04 17:51
 * Desc: TRADE 用户SERVER
 */
namespace App\Controller;
use App\Common\Util\Redis;
use App\Common\Util\Sms;
use App\Common\Util\HashId;
use App\Common\Util\RongCloud;
use App\Model\RegionModel;
use App\Model\SignDaysModel;
use App\Model\SignHistoryModel;
use App\Model\UserAddressModel;
use App\Model\UserAssetsLogModel;
use App\Model\UserAssetsModel;
use App\Model\UserExtModel;
use App\Model\UserModel;

class Customer extends Base {
    public function __construct(){
        parent::__construct();
    }

    /*发送手机验证码*/
    public function smsCode(){
//        $this->param['tel'] = '17620135606';
//        $this->param['token'] = sha1(md5('17620135606'.APP_SECRET));
        $needParam = array(
            'tel'=>array('msg'=>'tel参数异常','type'=>'tel'),
            'token'=>array('msg'=>'token参数异常','type'=>'str')
        );
        $this->regArguments($needParam,$this->param);
        $this->regToken($this->param['token'],$this->param['tel']);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }

        $this->redis = new Redis();
        $rkey = 'SMS-CODE-'.$this->param['tel'];
        $redisGets = $this->redis->client->hmget($rkey,['smsCode','sendTime']);
        $timeNow = time();
        $overTime = $timeNow - $redisGets[1];
        //60秒内，不允许重复发送短息
        if($overTime<60){
            $leftTime = 60 - $overTime;
            return $this->fjson(['code'=>1,'msg'=>'发送过于频繁，'.$leftTime.'秒后再试']);
        }
        //5分钟内同类型的验证码保持相同
        if($overTime<300){
            $code = $redisGets[0];
        }else{
            $code = rand(100000,999999);
        }
        $rdata = ['smsCode'=>$code,'sendTime'=>time()];
        $this->redis->client->hmset($rkey,$rdata);
        $sms = new Sms();
        $resq = $sms->smsSend($this->param['tel'],$code,'checkCodeTplId');
        if($resq->Code && $resq->Code == 'OK'){
            return $this->fjson($this->outData);
        }else{
            return $this->fjson(['code'=>1,'msg'=>$resq->Message]);
        }
    }
    /*用户注册*/
    public function register(){
//        $this->param['tel'] = '17620135606';
//        $this->param['passwd'] = 'hufeng';
//        $this->param['smsCode'] = '718365';
//        $this->param['token'] = sha1(md5('17620135606'.APP_SECRET));
        $needParam = array(
            'tel'=>array('msg'=>'tel参数异常','type'=>'tel'),
            'passwd'=>array('msg'=>'passwd参数异常','type'=>'str'),
            'smsCode'=>array('msg'=>'scode参数异常','type'=>'str'),
            'token'=>array('msg'=>'token参数异常','type'=>'str'),
        );
        $this->regArguments($needParam,$this->param);
        $this->regToken($this->param['token'],$this->param['tel']);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $this->regSmsCode($this->param['tel'],$this->param['smsCode']);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }

        //检测手机号是否存在
        $uModel = new UserModel();
        $uRes = $uModel->findData(['tel'=>$this->param['tel']],['id']);
        if($uRes){
            return $this->fjson(['code'=>1,'msg'=>'手机号已注册']);
        }
        //注册
        $userInData = [
            'open_id'=>0,
            'nick_name'=>$this->param['tel'],
            'tel'=>$this->param['tel'],
            'passwd'=>md5($this->param['passwd']),
            'avatar'=>DEFAULT_AVATAR,
            'addtime'=>$this->timeNow,
        ];
        $uid = $uModel->insertData($userInData);
        //创建openId
        $hashId = new HashId();
        $suid = $hashId->build($uid);
        //获取rongToken
        $rc = new RongCloud();
        $rcRes = $rc->getToken($uid,$this->param['tel'],DEFAULT_AVATAR);
        $uModel->editData(['id'=>$uid],['open_id'=>$suid,'rong_token'=>$rcRes->token]);

        //TODO 注册奖励
        $this->registerPrize($uid);

        $info = $this->loginInfo(['id'=>$uid]);
        $this->outData['data'] = $info;
        return $this->fjson($this->outData);
    }
    //注册奖励
    protected function registerPrize($uid){
        //赠送100万游戏币
        $uaModel = new UserAssetsModel();
        $uaModel->addAssets($uid,1000000,BALANCE_MONEY,BALANCE_ENABLE,'新注册用户赠送');
        return;
    }


    /*用户账号密码登录*/
    public function login(){
//        $this->param['tel'] = '17620135606';
//        $this->param['passwd'] = 'hufeng';
//        $this->param['token'] = sha1(md5($this->param['tel'].APP_SECRET));
        $needParam = array(
            'tel'=>array('msg'=>'tel参数异常','type'=>'tel'),
            'passwd'=>array('msg'=>'passwd参数异常','type'=>'str'),
            'token'=>array('msg'=>'token参数异常','type'=>'str')
        );
        $this->regArguments($needParam,$this->param);
        $this->regToken($this->param['token'],$this->param['tel']);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }

        $userWhere = [
            'tel'=>$this->param['tel']
        ];
        $userModel = new UserModel();
        $userRes = $userModel->findData($userWhere);
        if(strtolower($userRes['passwd']) == md5($this->param['passwd'])){
            $info = $this->loginInfo($userWhere);
            if($info['status']!=1){
                return $this->fjson(['code'=>3,'msg'=>'抱歉，您的账号被冻结']);
            }
            return $this->fjson(['code'=>0,'msg'=>'登录成功','info'=>$info]);
        }else{
            if($userRes){
                return $this->fjson(['code'=>3,'msg'=>'密码错误']);
            }else{
                return $this->fjson(['code'=>3,'msg'=>'账号不存在，请注册']);
            }
        }
    }
    //用户登录返回的信息
    protected function loginInfo($where){
        $userModel = new UserModel();
        $userRes = $userModel->findData($where);
        if(!$userRes){
            return [];
        }
        //记录最后登录的IP,和登录时间
        $ueModel = new UserExtModel();
        $ueModel->loginData($userRes['id'],$this->get_client_ip(),$this->timeNow);
        $info = [
            'openId'=>$userRes['open_id'],
            'nickName'=>$userRes['nick_name'],
            'tel'=>$userRes['tel'],
            'sex'=>$userRes['sex'],
            'realName'=>$userRes['real_name'],
            'avatar'=>$userRes['avatar'],
            'rongToken'=>$userRes['rong_token'],
            'status'=>$userRes['status']
        ];
        return $info;
    }
    /*验证验证码*/
    protected function regSmsCode($tel,$code){
        $this->redis = new Redis();
        $rkey = 'SMS-CODE-'.$tel;
        $redisGets = $this->redis->client->hmget($rkey,['smsCode','sendTime']);
        $timeNow = time();
        $overTime = $timeNow - $redisGets[1];
        if($overTime<1512484831){
            if($code == $redisGets[0]){
                $rdata = ['smsCode'=>$redisGets[0],'sendTime'=>1];
                $this->redis->client->hmset($rkey,$rdata);
            }else{
                $this->outData = ['code'=>1,'msg'=>'验证码错误，请重新输入'];
            }
        }else{
            $this->outData = ['code'=>1,'msg'=>'验证码已失效，请重新获取验证码'];
        }
        return;
    }
    /*记录用户APP版本信息*/
    public function updateAppVer(){
//        $this->param['openId'] = 'lY1v26A62KM1Kl';
//        $this->param['os'] = 'ios';
//        $this->param['appVer'] = '1.01';
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常','type'=>'str'),
            'os'=>array('msg'=>'os参数异常','type'=>'str'),
            'appVer'=>array('msg'=>'appVer参数异常','type'=>'str'),
        );
        $this->regArguments($needParam,$this->param);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }
        $ueModel = new UserExtModel();
        $ueModel->appVerData($uid,$this->param['os'],$this->param['appVer']);
        return $this->fjson($this->outData);
    }
    /*实名认证*/
    public function getRealAuth(){
//        $this->param['openId'] = 'lY1v26A62KM1Kl';
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常')
        );
        $this->regArguments($needParam,$this->param);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }
        $uRes = $uModel->findData(['id'=>$uid]);
        $info = [];
        $info['realName'] = $uRes['real_name'];
        $info['cardNo'] = $uRes['card_no'];
        $info['isAuth'] = in_array($uRes['real_check'],[1,2])  ? true : false;
        $tipsArr = ['0'=>'*为了您的账号安全，请进行实名认证','1'=>'*实名认证审核中','2'=>'*实名认证审核通过'];
        if($uRes['real_check'] == 3){
            $ueModel = new UserExtModel();
            $ueRes = $ueModel->userAllData($uid);
            $tips = '*审核未通过：'.$ueRes['authReason'];
        }else{
            $tips = $tipsArr[$uRes['real_check']];
        }
        $info['tip'] = $tips;
        $this->outData['data'] = $info;
        return $this->fjson($this->outData);
    }
    /*检测用户状态*/
    public function userStatus(){
//        $this->param['openId'] = 'lY1v26A62KM1Kl';
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常')
        );
        $this->regArguments($needParam,$this->param);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }
        $uRes = $uModel->findData(['id'=>$uid]);
        if($uRes['status'] != 1){
            return $this->fjson(['code'=>1,'msg'=>'账号被冻结']);
        }
        return $this->fjson($this->outData);
    }

    /*设置用户信息*/
    public function resetPwd(){
        $needParam = array(
            'tel'=>array('msg'=>'tel参数异常','type'=>'tel'),
            'passwd'=>array('msg'=>'passwd参数异常','type'=>'str'),
            'smsCode'=>array('msg'=>'smsCode参数异常','type'=>'str'),
            'pwdType'=>array('msg'=>'pwdType参数异常','type'=>'int'),
            'token'=>array('msg'=>'token参数异常','type'=>'str')
        );
        $this->regArguments($needParam,$this->param);
        $this->regToken($this->param['token'],$this->param['tel']);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $this->regSmsCode($this->param['tel'],$this->param['smsCode']);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }

        $uModel = new UserModel();
        $uRes = $uModel->findData(['tel'=>$this->param['tel']],['id']);
        if($this->param['pwdType'] == 1){
            $uModel->editData(['id'=>$uRes['id']],['passwd'=>md5($this->param['passwd'])]);
        }else{
            $uModel->editData(['id'=>$uRes['id']],['safe_passwd'=>md5($this->param['passwd'])]);
        }
        return $this->fjson($this->outData);

    }
    public function setNickName(){
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常','type'=>'str'),
            'nickName'=>array('msg'=>'nickName参数异常','type'=>'str'),
            'token'=>array('msg'=>'token参数异常','type'=>'str')
        );
        $this->regArguments($needParam,$this->param);
        $this->regToken($this->param['token'],$this->param['openId']);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }
        $uModel->editData(['id'=>$uid],['nick_name'=>$this->param['nickName']]);
        return $this->fjson(['code'=>0,'msg'=>'昵称设置成功']);
    }
    public function setAvatar(){
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常','type'=>'str'),
            'avatar'=>array('msg'=>'nickName参数异常','type'=>'str'),
            'token'=>array('msg'=>'token参数异常','type'=>'str')
        );
        $this->regArguments($needParam,$this->param);
        $this->regToken($this->param['token'],$this->param['openId']);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }
        $uModel->editData(['id'=>$uid],['avatar'=>$this->param['avatar']]);
        return $this->fjson(['code'=>0,'msg'=>'头像设置成功']);
    }
    public function setRealAuth(){
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常','type'=>'str'),
            'cardNo'=>array('msg'=>'cardNo参数异常','type'=>'str'),
            'realName'=>array('msg'=>'realName参数异常','type'=>'str'),
            'cardAddress'=>array('msg'=>'cardAddress参数异常','type'=>'str'),
            'cardFront'=>array('msg'=>'cardFront参数异常','type'=>'str'),
            'cardBack'=>array('msg'=>'cardBack参数异常','type'=>'str'),
            'cardHand'=>array('msg'=>'cardHand参数异常','type'=>'str'),
            'token'=>array('msg'=>'token参数异常','type'=>'str')
        );
        $this->regArguments($needParam,$this->param);
        $this->regToken($this->param['token'],$this->param['openId']);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }
        $this->editData(['uid'=>$uid],['real_name'=>$this->param['realName'],'card_no'=>$this->param['cardNo']]);
        $this->userRealData($uid,$this->param['cardAddress'],$this->param['cardFront'],$this->param['cardBack'],$this->param['cardHand']);
        return $this->fjson($this->outData);
    }
    public function setSex(){
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常','type'=>'str'),
            'sex'=>array('msg'=>'sex参数异常','type'=>int),
            'token'=>array('msg'=>'token参数异常','type'=>'str')
        );
        $this->regArguments($needParam,$this->param);
        $this->regToken($this->param['token'],$this->param['openId']);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }
        $uModel->editData(['id'=>$uid],['sex'=>$this->param['sex']]);
        return $this->fjson(['code'=>0,'msg'=>'性别设置成功']);
    }
    /*签到*/
    public function sign(){
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常','type'=>'str'),
            'token'=>array('msg'=>'token参数异常','type'=>'str')
        );
        $this->regArguments($needParam,$this->param);
        $this->regToken($this->param['token'],$this->param['openId']);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }

        $this->redis = new Redis();
        $lockKey = LOCK_USER_BALANCE.$uid;
        if(!$this->redis->getLock($lockKey)){
            return $this->fjson(['code'=>1,'msg'=>'您已签到成功']);
        }

        //判断今天是否签到
        $shModel = new SignHistoryModel();
        $IsSignToday = $shModel->todaySign($uid);
        if($IsSignToday){
            $this->redis->removeLock($lockKey);
            return $this->fjson(['code'=>1,'msg'=>'您已签到成功']);
        }
        //查询连续签到第几天
        $sdModel = new SignDaysModel();
        $signDays = $sdModel->signDays($uid);

        //获得金币总额
        $signSettings = $this->getConf('business','signSettings');
        $getTotalCoin = 0;
        foreach ($signSettings as $key=>$val){
            if($signDays+1 >= $key){
                $getTotalCoin = $val['Intergral'];
            }
        }
        $shInData = [
            'uid'=>$uid,
            'approved_coin'=>$getTotalCoin,
            'addtime'=>$this->timeNow,
        ];
        //插入签到记录
        $shModel->insertData($shInData);
        //更新签到天数
        $sdModel->recordDays($uid,$signDays+1);
        //记录用户资金明细
        $uaModel = new UserAssetsModel();
        $uaModel->addAssets($uid,$getTotalCoin,BALANCE_COIN,BALANCE_ENABLE,'签到奖励');
        $this->outData['coin'] = $getTotalCoin;
        $this->redis->removeLock($lockKey);
        return $this->fjson($this->outData);
    }
    public function getSignData(){
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常','type'=>'str')
        );
        $this->regArguments($needParam,$this->param);
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }

        $signSet = $this->getConf('business','signSettings');
        $sdModel = new SignDaysModel();
        $signDays = $sdModel->signDays($uid);
        $settings = [];
        foreach ($signSet as $key=>$val){
            $arr = [];
            $arr['isActive'] = $signDays>=$key ? true : false;
            $arr['coin'] = $val['Intergral'];
            $arr['days'] = $val['Days'];
            $settings[] = $arr;
            if($signDays+1>=$key){
                $nextCoin = $val['Intergral'];
            }
        }
        $shModel = new SignHistoryModel();
        $isSignToday = $shModel->todaySign($uid);

        $this->outData['isSignToday'] = $isSignToday;
        $this->outData['signDays'] = $signDays;
        $this->outData['nextCoin'] = $nextCoin;
        $this->outData['settings'] = $settings;
        return $this->fjson($this->outData);
    }

    /*各种资产明细*/
    //会员资产总额
    public function getAssets(){
        //余额，金币
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常','type'=>'str'),
            'assetsType'=>array('msg'=>'assetsType参数异常','type'=>'int')
        );
        $this->regArguments($needParam,$this->param);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }

        $uaModel = new UserAssetsModel();
        $ualModel = new UserAssetsLogModel();
        //剩余资产
        $uaRes = $uaModel->findData(['uid'=>$uid,'type'=>$this->param['assetsType']],['money']);
        $totalBalance = $uaRes['money'];
        //收入资产总额
        $inBalance = $ualModel->sumData(['uid'=>$uid,'type'=>$this->param['assetsType'],'change_money[>]'=>0],['change_money']);
        //支出资产总额
        $outBalance = $ualModel->sumData(['uid'=>$uid,'type'=>$this->param['assetsType'],'change_money[<]'=>0],['change_money']);
        $this->outData['totalBalance'] = $totalBalance;
        $this->outData['inBalance'] = $inBalance;
        $this->outData['outBalance'] = $outBalance;
        return $this->fjson($this->outData);
    }
    //资金明细
    public function assetsList(){
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常','type'=>'str'),
            'pageIndex'=>array('msg'=>'page参数异常','type'=>'int'),
            'pageSize'=>array('msg'=>'ps参数异常','type'=>'int'),
            'assetsType'=>array('msg'=>'assetsType参数异常','type'=>'int')
        );
        $this->regArguments($needParam,$this->param);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }

        $mhWhere = [
            'uid'=>$uid,
            'type'=>BALANCE_COIN,
            'status'=>BALANCE_ENABLE,
            'type'=>$this->param['assetsType'],
            'LIMIT' => [($this->param['pageIndex']-1)*$this->param['pageSize'], $this->param['pageSize']],
            'ORDER'=>['id'=>'DESC']
        ];
        $ualModel = new UserAssetsLogModel();
        $mhList = $ualModel->queryData($mhWhere,['change_money','left_money','memo','addtime']);
        $datas = [];
        foreach ($mhList as $val){
            $arr = [];
            $arr['changeMoney'] = $val['change_money'];
            $arr['leftMoney'] = $val['left_money'];
            $arr['memo'] = $val['memo'];
            $arr['addTime'] = date('Y-m-d',strtotime($val['addtime']));
            $datas[] = $arr;
        }
        $this->outData['data'] = $datas;
        unset($mhWhere['LIMIT']);
        unset($mhWhere['ORDER']);
        $totalNum = $ualModel->getTotalNum($mhWhere);
        $this->outData['totalPages'] = ceil($totalNum/$this->param['pageSize']);
        return $this->fjson($this->outData);
    }

    /*用户地址*/
    public function area(){
        $needParam = array(
            'pid'=>array('msg'=>'pid参数异常','type'=>'int')
        );
        $this->regArguments($needParam,$this->param);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $rModel = new RegionModel();
        $pid = $this->param['pid'] ? $this->param['pid'] : 0;
        $this->outData['data'] = $rModel->queryData(['pid'=>$pid],['id','name']);
        return $this->fjson($this->outData);
    }
    //添加编辑收货地址
    public function setAddress(){
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常','type'=>'str'),
            'aid'=>array('msg'=>'aid参数异常','type'=>'int'),
            'uname'=>array('msg'=>'uname参数异常','type'=>'str'),
            'tel'=>array('msg'=>'tel参数异常','type'=>'tel'),
            'pname'=>array('msg'=>'pname参数异常','type'=>'str'),
//            'cname'=>array('msg'=>'nickName参数异常','type'=>'str'),
//            'aname'=>array('msg'=>'nickName参数异常','type'=>'str'),
            'info'=>array('msg'=>'info参数异常','type'=>'str'),
            'default'=>array('msg'=>'default参数异常','type'=>'int'),
            'token'=>array('msg'=>'token参数异常','type'=>'str')
        );
        $this->regArguments($needParam,$this->param);
        $this->regToken($this->param['token'],$this->param['openId']);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }

        $uaddModel = new UserAddressModel();
        //默认地址
        if($this->param['default'] == 2){
            $uaddModel->editData(['uid'=>$uid],['is_default'=>1]);
        }

        $optData = [
            'uid'=>$uid,
            'uname'=>$this->param['uname'],
            'tel'=>$this->param['tel'],
            'pname'=>$this->param['pname'],
            'cname'=>$this->param['cname'] ? $this->param['cname'] : '',
            'aname'=>$this->param['aname'] ? $this->param['aname'] : '',
            'info'=>$this->param['info'],
            'is_default'=>$this->param['default'],
            'is_del'=>1
        ];
        if($this->param['aid']){
            //更新
            $uaddModel->editData(['id'=>$this->param['aid']],$optData);
        }else{
            //新增
            $uaddModel->insertData($optData);
        }
        return $this->fjson($this->outData);
    }
    //删除收货地址
    public function delAddress(){
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常','type'=>'str'),
            'aid'=>array('msg'=>'aid参数异常','type'=>'int'),
            'token'=>array('msg'=>'token参数异常','type'=>'str')
        );
        $this->regArguments($needParam,$this->param);
        $this->regToken($this->param['token'],$this->param['openId']);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }
        $uaddModel = new UserAddressModel();
        $uaRes = $uaddModel->findData(['uid'=>$uid,'id'=>$this->param['aid'],'is_default'=>1]);
        if($uaRes){
            $uaddModel->editData(['id'=>$this->param['aid']],['is_del'=>2]);
        }else{
            return $this->fjson(['code'=>1,'msg'=>'不能删除默认地址']);
        }
        return $this->fjson($this->outData);
    }
    //获取收货地址
    public function myAddress(){
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常','type'=>'str'),
        );
        $this->regArguments($needParam,$this->param);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }
        $uaddModel = new UserAddressModel();
        $where = [
            'uid'=>$uid,
            'is_del'=>1,
            'ORDER'=>['is_default'=>'DESC']
        ];
        $list = $uaddModel->queryData($where);
        $this->outData['data'] = $list;
        return $this->fjson($this->outData);
    }

    /*todo 绑定第三方账号*/
    public function bindThirdAccount(){
        return;
        $needParam = array(
            'provideName'=>array('msg'=>'provideName参数异常'),
            'openId'=>array('msg'=>'openId参数异常'),
            'userName'=>array('msg'=>'userName参数异常'),
            'nickName'=>array('msg'=>'nickName参数异常'),
            'avatar'=>array('msg'=>'avatar参数异常'),
        );
        $this->regArguments($needParam,$this->param);
        $this->checkTel($this->param['userName']);
        if(!$this->outData['result']){
            return $this->fjson($this->outData);
        }
        //如果手机号已存在，直接绑定
        $uModel = new JsCustomerModel();
        $uRes = $uModel->findData(['Username'=>$this->param['userName']],['Id','Username','TrueName','NickName']);
        if($uRes['Id']){
            $utModel = new JsCustomerThirdModel();
            $utRes = $utModel->findData(['ExternalIdentifier'=>$this->param['openId'],'ProviderSystemName'=>$this->param['provideName']],['Id']);
            if(!$utRes['Id']){
                $utInData = [
                    'CustomerId'=>$uRes['Id'],
                    'NickName'=>$this->param['nickName'],
                    'Avatar'=>$this->param['avatar'],
                    'ExternalIdentifier'=>$this->param['openId'],
                    'ProviderSystemName'=>$this->param['provideName'],
                ];
                $utModel->insertData($utInData);
            }
            $userWhere = [
                'Username'=>$this->param['userName'],
                'Active'=>1,
                'Deleted'=>0,
            ];
            $info = $this->loginInfo($userWhere);
            if(!$info){
                return $this->fjson(['status'=>3,'msg'=>'抱歉，您的账号被冻结']);
            }
            return $this->fjson(['status'=>1,'msg'=>'请求成功','info'=>$info]);
        }else{
            return $this->fjson(['status'=>2,'msg'=>'手机号不存在']);
        }
    }
    /*todo 第三方账号注册*/
    public function thirdRegister(){
        return;
        $needParam = array(
            'provideName' => array('msg' => 'provideName参数异常'),
            'openId' => array('msg' => 'openId参数异常'),
            'userName' => array('msg' => 'userName参数异常'),
            'userPwd' => array('msg' => 'userPwd参数异常'),
            'recommandUserName' => array('msg' => 'recommandUserName参数异常'),
            'nickName' => array('msg' => 'nickName参数异常'),
            'avatar' => array('msg' => 'avatar参数异常'),
            'smsCode' => array('msg' => 'smsCode参数异常'),
            'token' => array('msg' => 'token参数异常'),
        );
        $this->regArguments($needParam, $this->param);
        $this->checkTel($this->param['userName']);
        $this->checkTel($this->param['recommandUserName']);
        $this->regToken($this->param['token'], $this->param['userName']);
        if (!$this->outData['result']) {
            return $this->fjson($this->outData);
        }

        $this->redis = new Redis();
        $rkey = 'SMS-CODE-' . $this->param['userName'];
        $redisGets = $this->redis->client->hmget($rkey, ['smsCode', 'sendTime']);
        $PasswordSalt = rand(111111, 999999);

        //检测手机号是否存在
        $uModel = new JsCustomerModel();
        $uRes = $uModel->findData(['Username' => $this->param['userName']], ['Id']);
        if ($uRes) {
            return $this->fjson(['result' => false, 'msg' => '手机号已被注册']);
        }
        $uRes = $uModel->findData(['Username' => $this->param['recommandUserName']], ['Id']);
        if (!$uRes) {
            return $this->fjson(['result' => false, 'msg' => '推荐人不存在']);
        }
        $puid = $uRes['Id'];
        if ($redisGets[0] && $this->param['smsCode'] == $redisGets[0]) {
            //注册
            $userInData = [
                'CustomerGuid' => 0,
                'Username' => $this->param['userName'],
                'TrueName' => '未知',
                'NickName' => $this->param['nickName'],
                'Password' => sha1('111111' . $PasswordSalt),
                'ActionPwd' => sha1('000000' . $PasswordSalt),
                'PasswordFormatId' => 1,
                'PasswordSalt' => $PasswordSalt,
                'AdminComment' => '邀请注册',
                'Active' => 1,
                'Deleted' => 0,
                'IsSystemAccount' => 0,
                'LastIpAddress' => $this->get_client_ip(),
                'CreatedOn' => date('Y-m-d H:i:s'),
                'ParentId' => $puid,
                'PartnerId' => 0,
                'RecommandId' => $puid,
                'IsStock' => 0,
                'IsEcommerce' => 0,
                'IsConsummer' => 0,
                'IsAuthenticate' => 0,
                'TeamNum' => 1,
                'Treasure' => 0,
                'IntergralRate' => 0,
                'HasShoppingCartItems' => 0,
                'IsTaxExempt' => 0,
                'AffiliateId' => 0,
                'VendorId' => 0,
            ];
            $uid = $uModel->insertData($userInData);
            $hashId = new HashId();
            $suid = $hashId->build($uid);
            $uModel->editData(['Id' => $uid], ['CustomerGuid' => $suid]);
            //记录用户扩展信息
            $uaModel = new JsCustomerAttributeModel();
            $uaModel->insertData(['EntityId'=>$uid,'KeyGroup'=>'Customer','Key'=>'Avatar','Value'=>$this->param['avatar']]);
            $uaModel->insertData(['EntityId'=>$uid,'KeyGroup'=>'Customer','Key'=>'RongCustomerId','Value'=>$uid]);
            $rc = new RongCloud();
            $rcRes = $rc->getToken($uid,$this->param['nickName'],$this->param['avatar']);
            $uaModel->insertData(['EntityId'=>$uid,'KeyGroup'=>'Customer','Key'=>'RongRoken','Value'=>$rcRes->token]);
            //用户推荐关系
            $crModel = new JsCustomerRecommendsModel();
            $crRes = $crModel->findData(['uid' => $puid]);
            $pidStr = $crRes['pids'] ? ',' . $puid . $crRes['pids'] : ',' . $puid . ',';
            $crModel->insertData(['uid' => $uid, 'pids' => $pidStr]);
            //用户推荐人团队数量
            $fpidStr = trim($pidStr, ',');
            $fpidArr = explode(',', $fpidStr);
            $uModel->editData(['Id' => $fpidArr], ['TeamNum[+]' => 1]);

            //奖励购物券
            $mhModel = new JsMoneyHistoryModel();
            $mhModel->rewardCoupon([$uid,$fpidArr[0],$fpidArr[1]],$this->param['userName']);

            //绑定第三方信息
            $utModel = new JsCustomerThirdModel();
            $utRes = $utModel->findData(['ExternalIdentifier'=>$this->param['openId'],'ProviderSystemName'=>$this->param['provideName']],['Id']);
            if(!$utRes){
                $utInData = [
                    'CustomerId'=>$uid,
                    'NickName'=>$this->param['nickName'],
                    'Avatar'=>$this->param['avatar'],
                    'ExternalIdentifier'=>$this->param['openId'],
                    'ProviderSystemName'=>$this->param['provideName'],
                ];
                $utModel->insertData($utInData);
            }
            return $this->fjson($this->outData);
        }else{
            return $this->fjson(['status'=>2,'msg'=>'验证码不正确，请重新输入验证码']);
        }
    }
    /*todo 第三方账号登录*/
    public function thirdLogin(){
        return;
        $needParam = array(
            'customerId'=>array('msg'=>'uid参数异常'),
        );
        $this->regArguments($needParam,$this->param);
        if (!$this->outData['result']) {
            return $this->fjson($this->outData);
        }
        $uid = $this->getCustomId($this->param['customerId']);
        if(!$uid){
            return $this->fjson($this->outData);
        }
        $utModel = new JsCustomerThirdModel();
        $utRes = $utModel->queryData(['CustomerId'=>$uid],['NickName','Avatar','ExternalIdentifier','ProviderSystemName']);
        $info = [];
        foreach ($utRes as $val){
            $arr = [];
            $arr['NickName'] = $val['NickName'];
            $arr['Avatar'] = $val['Avatar'];
            $arr['ExternalId'] = $val['ExternalIdentifier'];
            $arr['ProviderName'] = str_replace('_yunlutong','', $val['ProviderSystemName']);
            $info[] = $arr;
        }
        $this->outData['info'] = $info;
        return $this->fjson($this->outData);
    }
    /*todo 解除第三方账号绑定*/
    public function removeThird(){
        return;
        $needParam = array(
            'customerId'=>array('msg'=>'uid参数异常'),
            'externalId'=>array('msg'=>'eid参数异常'),
        );
        $this->regArguments($needParam,$this->param);
        if (!$this->outData['result']) {
            return $this->fjson($this->outData);
        }
        $uid = $this->getCustomId($this->param['customerId']);
        if(!$uid){
            return $this->fjson($this->outData);
        }
        $utModel = new JsCustomerThirdModel();
        $utModel->delData(['CustomerId'=>$uid,'ExternalIdentifier'=>$this->param['externalId']]);
        return $this->fjson($this->outData);
    }
    /*todo 刷新融云token*/
    public function refreshRongToken(){
        return;
        $needParam = array(
            'customerId'=>array('msg'=>'uid参数异常')
        );
        $this->regArguments($needParam,$this->param);
        if(!$this->outData['result']){
            return $this->fjson($this->outData);
        }
        $uid = $this->getCustomId($this->param['customerId']);
        if(!$uid){
            return $this->fjson($this->outData);
        }
        $uModel = new JsCustomerModel();
        $uaModel = new JsCustomerAttributeModel();
        $uRes = $uModel->findData(['Id'=>$uid],['Username','NickName','TrueName']);
        if(!$uRes){
            return $this->fjson(['result'=>false,'msg'=>'会员不存在']);
        }
        $username = $uRes['TrueName'] != '未知' ? $uRes['TrueName'] : ($uRes['NickName'] ? $uRes['NickName'] : $uRes['Username']);
        $avatar = $uaModel->findData(['EntityId'=>$uid,'Key'=>'Avatar'],['Value']);
        $rcuid = $uaModel->findData(['EntityId'=>$uid,'Key'=>'RongCustomerId'],['Value']);
        $headImg = $avatar['Value'] ? $avatar['Value'] : DEFAULT_AVATAR;
        $rc = new RongCloud();
        $rc->refreshToken($rcuid,$username,$headImg);
        $rcRes = $rc->getToken($rcuid,$username,$headImg);
        $uaModel->insertData(['EntityId'=>$uid,'KeyGroup'=>'Customer','Key'=>'RongRoken','Value'=>$rcRes->token]);
        return $this->fjson(['result'=>true,'msg'=>$rcRes->token]);
    }

}
